<!-- 用户管理页面 -->
<template>
    <!-- 单根 -->
    <div>
        <!-- 操作栏 -->
        <el-row :gutter="20">
            <el-col :span="4">
                <el-input v-model="searchUsername" @blur="loadUser" clearable>
                    <template #prepend>用户名</template>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-input v-model="searchNickname" @blur="loadUser" clearable>
                    <template #prepend>昵称</template>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-input v-model="searchRoleName" @blur="loadUser" clearable>
                    <template #prepend>角色</template>
                </el-input>
            </el-col>
            <div style="flex-grow: 1;"></div>
            <el-col :span="4">
                <el-button plain @click="addUser" type="primary">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 用户表 -->
        <el-table ref="userTableRef" :data="userDatas" highlight-current-row style="width: 100%;"
                  v-loading="userTableLoading" stripe>
            <el-table-column prop="id" label="id" width="50"/>
            <el-table-column prop="username" label="用户名" width="160"/>
            <el-table-column prop="nickname" label="昵称" width="160"/>
            <el-table-column prop="phone" label="手机号" width="120"/>
            <el-table-column prop="isBan" label="是否禁用" width="120">
                <template #default="scope">
                    <span style="color:red" v-if="scope.row.isBan">是</span>
                    <span style="color:green" v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column label="角色">
                <template #default="scope">
                    <el-tag v-for="role in scope.row.roles" >
                        {{ role.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="info" size="small" plain @click="editUser(scope.row)">编辑</el-button>
                    <el-button type="primary" size="small" plain @click="bindRole(scope.row)">绑定角色</el-button>
                    <el-button type="warning" size="small" plain @click="banUser(scope.row)">{{
                            scope.row.isBan ? '解禁' : '禁用'
                        }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页管理 -->
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 100]"
                       :pager-count="10"
                       :total="totalUser" layout="total, sizes, prev, pager, next" @size-change="sizeChange"
                       @current-change="currentChange"/>
        <!-- 用户对话框 -->
        <el-dialog v-model="userDialogVisible" :title="userDialogTitle" width="400px" draggable>
            <el-form v-if="userDialogForm" v-model="userDialogForm" label-width="auto">
                <el-form-item label="用户名">
                    <el-input v-model="userDialogForm.username" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="userDialogForm.nickname"/>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="userDialogForm.phone"/>
                </el-form-item>
                <el-form-item label="密码" v-if="userDialogType == UserDialogType.add">
                    <el-input v-model="userDialogForm.password" type="password" autocomplete="off"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <span>
                    <el-button @click="userDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="userDialogFormSubmit">
                        提交
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 绑定角色对话框 -->
        <el-dialog v-model="bindRoleDialogVisible" title="绑定角色" width="400px" draggable>
            <el-form v-model="bindRoleDialogForm" label-width="auto">
                <el-form-item label="用户id">
                    <el-input v-model="bindRoleDialogForm.id" disabled/>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="bindRoleDialogForm.username" disabled/>
                </el-form-item>
                <el-form-item label="绑定角色">
                    <el-checkbox-group v-model="bindRoleDialogForm.roles">
                        <el-checkbox v-for="role in roleCheckBox" :label="role.id">{{ role.name }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="bindRoleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="bindRoleDialogFormConfirm">
                    提交
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ElMessage, ElTable} from 'element-plus';
import {onMounted, ref} from 'vue';
import {myAxios} from '../assets/ts/my-axios'
import {UserInfo, UserDetail} from '../assets/ts/user-manager'

// 生命周期 - 挂载
onMounted(() => {
    loadUser()
})

// 用户数据
const userDatas = ref<Array<UserInfo>>([])
const userTableRef = ref<InstanceType<typeof ElTable>>()
const userTableLoading = ref(false)

// 分页数据
const currentPage = ref(0)
const pageSize = ref(20)
const totalUser = ref(0)
const searchUsername = ref('')
const searchNickname = ref('')
const searchRoleName = ref('')

// 页大小变化
function sizeChange(size: number) {
    pageSize.value = size
    loadUser()
}

// 当前页变化
function currentChange(current: number) {
    currentPage.value = current
    loadUser()
}

// 加载用户表
function loadUser() {
    userTableLoading.value = true
    let params = {
        page: currentPage.value,
        limit: pageSize.value,
        username: searchUsername.value,
        nickname: searchNickname.value,
        roleName: searchRoleName.value,
    }
    myAxios.get('/user/page', {params: params})
        .then((response) => {
            if (response.data.code == -1) {
                ElMessage.error(response.data.message)
            } else {
                userDatas.value = response.data.data.records
                currentPage.value = response.data.data.current
                totalUser.value = response.data.data.total
            }
        }).finally(() => {
        userTableLoading.value = false
    })
}

// ===================================== 用户对话框 ==========================================

enum UserDialogType { add, edit }

const userDialogVisible = ref(false)
const userDialogType = ref(UserDialogType.add)
const userDialogTitle = ref('')
const userDialogForm = ref<UserDetail>()
let userDialogFormSource: UserDetail

// 编辑用户
function editUser(userInfo: UserInfo) {
    loadRoleCheckBox()
    // 类型为编辑
    userDialogType.value = UserDialogType.edit
    userDialogTitle.value = '编辑用户'
    // 表单初始化
    userDialogFormSource = {...userInfo, roleIds: []}
    userInfo.roles.forEach((role: any) => {
        userDialogFormSource.roleIds.push(role.id)
    });
    userDialogFormReset()
    // 展示面板
    userDialogVisible.value = true
}

// 添加用户
function addUser() {
    loadRoleCheckBox()
    // 类型为编辑
    userDialogType.value = UserDialogType.add
    userDialogTitle.value = '添加用户'
    // 表单初始化
    userDialogFormSource = {id: 0, username: '', nickname: '', isBan: false, roleIds: []}
    userDialogFormReset()
    // 展示面板
    userDialogVisible.value = true
}

// 重置
function userDialogFormReset() {
    userDialogForm.value = userDialogFormSource
}

// 用户表单提交
function userDialogFormSubmit() {
    let apiUrl =
        userDialogType.value == UserDialogType.add ? '/user/add'
            : userDialogType.value == UserDialogType.edit ? 'user/edit'
                : ''
    myAxios.post(apiUrl, userDialogForm.value)
        .then((response) => {
            if (response.data.code == 0) {
                ElMessage.success('绑定成功')
                loadUser()
                userDialogVisible.value = false
            } else {
                ElMessage.error(response.data.message)
            }
        })
}

// ===================================== 绑定角色表单 ==========================================

const bindRoleDialogVisible = ref(false)
const bindRoleDialogForm = ref<any>({})

// 绑定角色
function bindRole(user: UserInfo) {
    loadRoleCheckBox()
    bindRoleDialogVisible.value = true
    bindRoleDialogForm.value.id = user.id
    bindRoleDialogForm.value.username = user.username
    bindRoleDialogForm.value.roles = []
    user.roles.forEach((role: any) => {
        bindRoleDialogForm.value.roles.push(role.id)
    });
}

// 加载角色选项
const roleCheckBox: any = ref([])

function loadRoleCheckBox() {
    myAxios.get('role/listAll')
        .then((response) => {
            if (response.data.code == 0) {
                roleCheckBox.value = response.data.data
            } else {
                ElMessage.error(response.data.message)
            }
        })
}

// 绑定角色提交
function bindRoleDialogFormConfirm() {
    let bindRoleFormParams = new URLSearchParams()
    bindRoleFormParams.set('userId', bindRoleDialogForm.value.id)
    bindRoleFormParams.set('roleIds', bindRoleDialogForm.value.roles)
    myAxios.post('/user/bindRole', bindRoleFormParams)
        .then((response) => {
            if (response.data.code == 0) {
                ElMessage.success('绑定成功')
                loadUser()
                bindRoleDialogVisible.value = false
            } else {
                ElMessage.error(response.data.message)
            }
        })
}

// 禁用/解禁角色
function banUser(userInfo: UserInfo) {
    myAxios.post('/user/ban', {
        userId: userInfo.id,
        isBan: !userInfo.isBan
    }, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .then((response) => {
                if (response.data.code == 0) {
                    ElMessage.success("提交成功")
                    loadUser()
                } else {
                    ElMessage.error(response.data.message)
                }
            }
        )
}

</script>

<style scoped>

.el-table {
    margin: 10px 0;
}

.el-checkbox-group {
    text-align: left;
}

.el-tag{
    margin: 5px;
}
</style>